/* 
 * AUTHOR: Kevin Lam
 */

package com.apps.ubc.cc.controller;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.apps.datastore.AccountInformationDatastore;
import com.apps.datastore.dao.SectionInformationObject;
import com.apps.services.CourseSummaryService;
import com.apps.ubc.cc.model.WorklistModel;

public class WorklistViewController extends HttpServlet {

	CourseSummaryService cs = new CourseSummaryService();
	AccountInformationDatastore d = new AccountInformationDatastore();

	public void doGet(HttpServletRequest req, HttpServletResponse resp) {
		String email = req.getParameter("email");
		Cookie[] cookies = req.getCookies();
		String user = null;
		for (int i = 0; i < cookies.length; i++) {
			if (cookies[i].getName().equals("user"))
				user = cookies[i].getValue();
		}
		if(user != null && (d.checkSubscriptionExists(email, user) || email.equals(user))) {
			List<SectionInformationObject> siol = d.getWorklistAsSIO(email);	
			String[] startEnd = cs.getStartEnd(siol);
			WorklistModel wm = new WorklistModel(email,startEnd[0],startEnd[1]);
		HttpSession s = req.getSession();
		s.setAttribute("worklist", wm);
		try {
			req.getRequestDispatcher("/worklist.jsp").forward(req, resp);
		} catch (ServletException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		}
		else {
			try {
				req.getRequestDispatcher("/debug.jsp?msg=unauthorized").forward(req, resp);
			} catch (ServletException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
		}
		
	}
}
